package com.stylefeng.guns.core.support;

import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @author carloszhang
 *
 * 密码md5工具类
 *
 * 其他md5不使用此操作
 *
 */
public class CipherMd5Util {

    /**
     * 验证md5
     * @param srcData
     * @param hmac
     * @param key
     * @return
     */
    public static boolean verifyMd5(String srcData, String hmac, String key){
        String _crpy = cryptMd5(srcData, key);
        return StringUtils.equals(_crpy,hmac);
    }
    /**
     *
     * @param source
     * @param key
     * @return
     */
    public static String cryptMd5(String source, String key) {
        byte[] keyb;
        byte[] value;
        byte[] k_ipad = new byte[64];
        byte[] k_opad = new byte[64];
        try {
            keyb = key.getBytes("UTF-8");
            value = source.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            keyb = key.getBytes();
            value = source.getBytes();
        }
        Arrays.fill(k_ipad, keyb.length, 64, (new Integer(54)).byteValue());
        Arrays.fill(k_opad, keyb.length, 64, (new Integer(92).byteValue()));
        for (int i = 0; i < keyb.length; ++i) {
            k_ipad[i] = (byte) (keyb[i] ^ 0x36);
            k_opad[i] = (byte) (keyb[i] ^ 0x5C);
        }
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        md.update(k_ipad);
        md.update(value);
        byte[] dg = md.digest();
        md.reset();
        md.update(k_opad);
        md.update(dg, 0, 16);
        dg = md.digest();
        return toHex(dg);
    }

    public static String toHex(byte[] input) {
        if (input == null)
            return null;
        StringBuffer output = new StringBuffer(input.length * 2);
        for (int i = 0; i < input.length; ++i) {
            int current = input[i] & 0xFF;
            if (current < 16)
                output.append("0");
            output.append(Integer.toString(current, 16));
        }
        return output.toString();
    }

    public static void main(String[] args){
        System.out.println(CipherMd5Util.cryptMd5("888888","2000052"));
    }
}
